package com.henz4help.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;

import com.henz4help.app.common.AppInfo;
import com.henz4help.app.common.Constants;
import com.henz4help.app.common.HttpWorker;
import com.henz4help.app.common.Util;
import com.henz4help.app.db.HenzDBHelper;
import com.henz4help.app.db.domain.PersonalData;

public class LocSenderService extends Service {
	
	private static final int MSG_DO_WORKING = 99;
	private boolean mWorkerWorking;
	private boolean mFirstPassed;
	
	private HttpWorker mHttpWorker;
	
	public HenzDBHelper mDatabaseHelper;
	
	private Worker worker;
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	@Override
	public void onCreate() {
		Util.Log("LocSenderService : onCreate()");
		super.onCreate();
		mHttpWorker = new HttpWorker();
		mFirstPassed = false;
	}

	@Override
	public void onDestroy() {
		Util.Log("LocSenderService : onDestroy()");
		
		super.onDestroy();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Util.Log("LocSenderService : onStartCommand()");
		super.onStartCommand(intent, flags, startId);
		doJob();
		return START_NOT_STICKY;
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		Util.Log("LocSenderService : onConfigurationChanged()");
		super.onConfigurationChanged(newConfig);
	}
	
	
	private void doJob() {
		
		if(worker == null) {
			Util.Log("LocSenderService : Worker Start!!");
			mWorkerWorking = true;
			worker = new Worker();
			worker.start();
			return;
		}
		
		if(!mFirstPassed) {
			mFirstPassed = true;
			return;
		}
		
		if(mWorkerWorking){
			new NetWorker().execute();
		}
		
	}
	
	
	private void sendPersonalData() {
		mWorkerWorking = false;
		Context context = null;
		
		AppInfo appInfo = null;
		String phoneNum = null;
		
		HenzDBHelper databaseHelper = null;
		PersonalData data = null;
		
		
		Map<String, Object> jsonParams = null;
		List<Map<String, Object>> reportList = null;
		Map<String, Object> params = null;
		
		context = getApplicationContext();
		
		appInfo = AppInfo.getInstance(context);
		phoneNum = appInfo.getmPhoneNum();
		
		databaseHelper = HenzDBHelper.getInstance(context);
		data = databaseHelper.retrievePersonalData();
		
		
		jsonParams = new HashMap<String, Object>();
		reportList = new ArrayList<Map<String, Object>>();
		params = new HashMap<String, Object>();
		//params.put("email","sixvern@nate.com");
		params.put("email",data.email);
		params.put("phoneNum", phoneNum);
		/*
		params.put("long", mLongitude);
		params.put("lat", mLatitude);
		*/
		
		params.put("lat", data.latitude);
		params.put("long", data.longitude);
		params.put("address", data.address);
		
		params.put("type", "");
		params.put("name", data.firstName + " " + data.lastName);
		params.put("desc", "");
		//params.put("curTime", System.currentTimeMillis());
		params.put("regId", data.regId);
		params.put("curTime", new Date());
		
		reportList.add(params);
		jsonParams.put("reportList", reportList);
		
		//mHttpWorker.request("http://1-dot-henzmobile.appspot.com/report/add.json", params);
		//mHttpWorker.requestJson("http://1-dot-henzmobile.appspot.com/report/add.json", jsonParams);
		mHttpWorker.requestSingleJson("http://1-dot-henzmobile.appspot.com/report/addSingle.json", params);
		
		
		
		Intent intent = new Intent();
		intent.setAction(Constants.ACTION_SIGNAL_SEND);
		intent.putExtra(Constants.EXTRA_SIGNAL_SEND, Constants.VALUE_SIGNAL_SEND);
		sendBroadcast(intent);
		
		stopSelf();
	}
	
	private class Worker extends Thread {
		@Override
		public void run() {
			while(mWorkerWorking) {
				try {
					Thread.sleep(300);
					Util.Log("LocSenderService : Worker is working!!");
				} catch (InterruptedException e) {
					Util.Log("LocSenderService : " + e.toString());
				}
				Message msg = Message.obtain();
				msg.what = MSG_DO_WORKING;
				LocSenderService.this.handler.sendMessage(msg);
			}
		}		
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case MSG_DO_WORKING:
				doJob();
				break;
			}
		}		
	};
	
	private class NetWorker extends AsyncTask<Void, Void, Boolean> {
		
		//boolean isWorking = false;
		
		@Override
		protected void onPostExecute(Boolean result) {
			//isWorking = false;
			stopSelf();
		}
		
		@Override
		protected void onPreExecute() {
			//isWorking = true;
			super.onPreExecute();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			boolean result = false;
			sendPersonalData();
			return result;
		}
	}
}
